<template>
	<div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
		<div class="modal-content" @click.stop>
			<div class="modal-header">
				<span class="modal-title">{{ title }}</span>
				<span class="close-btn" @click="close">×</span>
			</div>

			<div class="modal-body">
				<div class="signature-area">
					<div class="signature-title">请在下方区域签名</div>
					<canvas :style="'width: '+ screenWidth +'px; height: '+ windowHeight  +'px'" canvas-id="signsss"
						id="signsss" class="signsss" disable-scroll :hidpi="false" @touchstart="touchstart"
						@touchmove="touchmove" @touchend="touchend" @touchcancel="touchcancel"></canvas>
				</div>
			</div>

			<div class="modal-footer">
				<button class="btn btn-cancel" @click="close">取消</button>
				<button class="btn btn-clear" @click="clear">清除</button>
				<button class="btn btn-submit" @click="save" :loading="this.loading">提交</button>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'SignatureModal',
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			title: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				drawing: false,
				hasSignature: false,
				canvasRect: null,

				markText: "",
				instance: null,
				ctx: null, //绘图图像
				points: [], //路径点集合
				pointsNum: [], //路径点集合
				path: "",
				flag: false,
				loading: false,
				screenWidth: 0,
				windowHeight: 0,
				signUrl: ''
			}
		},
		watch: {
			visible(newVal) {
				if (newVal) {
					this.$nextTick(() => {
						// this.initCanvas();
						// 生成水印内容
						// this.refreshMark();
						uni.getSystemInfo().then(systemInfo => {
							this.screenWidth = systemInfo.screenWidth;
							this.windowHeight = systemInfo.windowHeight;
							console.log(`屏幕宽度: ${this.screenWidth}px`);
							console.log(`屏幕可视高度: ${this.windowHeight}px`);
						})
						this.instance = this;
						this.init();
					});
				}
			}
		},
		onLoad() {

			console.log(uni.getSystemInfo());
		},
		methods: {
			goBack() {
				uni.$emit('isRefresh', this.signUrl)
				uni.navigateBack({
					delta: 1
				})
			},
			init() {
				this.ctx = uni.createCanvasContext("signsss", this.instance);
				this.ctx.lineWidth = 6;
				this.ctx.setFillStyle('#FF0000'); // 红色背景  
				this.ctx.lineCap = "round";
				this.ctx.lineJoin = "round";
				this.flag = false;
			},

			touchstart(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				this.points.push(startPoint);
				this.pointsNum.push(startPoint);
				this.ctx.beginPath();
				console.log(this.points);
			},

			touchmove(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
			},

			touchend(e) {
				this.points = [];
			},

			touchcancel(e) {
				touchend();
			},

			draw() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
				this.flag = true;
			},

			save() {
				// this.loading = true;
				const that = this;
				console.log(this.pointsNum);
				if (this.pointsNum.length < 3) {
					uni.$u.toast('请完成签名后再保存');
					return false;
				}
				uni.canvasToTempFilePath({
						x: 0,
						y: 0,
						width: 320 / 2, // 画布得宽度,单位px
						height: 566 / 2, // 画布得高度,单位px
						canvasId: "signsss",
						fileType: 'jpg',
						quality: 1.0,
						success: async function(res) {
							// res.tempFilePath 临时路径
							console.log(123, res.tempFilePath);

							// that.getShouxieEngurl(res.tempFilePath)
							// // 创建一个 Image 对象
							//  const img = new Image();
							//  // 确保图片已完全加载
							//  img.onload = function () {
							// // 创建一个 Canvas 元素
							// const canvas = document.createElement('canvas');
							// const ctx = canvas.getContext('2d');
							// // 设置 Canvas 的宽高等于图片的宽高
							// canvas.width = img.width;
							// canvas.height = img.height;
							// // 将图片绘制到 Canvas 上
							// ctx.drawImage(img, 0, 0);
							// // 获取图片的 base64 编码
							// const base64 = canvas.toDataURL('image/jpeg');
							// // 执行回调函数，将 base64 字符串作为参数传递出去
							// // callback(base64);
							// console.log('img', base64);
							//  }
							//  // 加载图片
							//  img.src = res.tempFilePath;

							const result = await that.uploadFilePromise(res.tempFilePath)
							// that.getShouxieEngurl(res.tempFilePath)
							// that.getShouxieEngurl('https://image.smjxyp.com' + result)
							that.$emit('submit', result)
							// that.goBack();
						},
						complete: function() {
							this.loading = false;
						},
					},
					this.instance
				);
			},
			//清空画布
			clear() {
				const that = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(false);
						that.flag = false;
						that.pointsNum = [];
					},
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					var filePath = this.fileName()
					uni.uploadFile({
						url: this.$imgUrl('api/common/upload'),
						filePath: url,
						name: 'file',
						success: (upres) => {
							console.log(upres);
							const obj = JSON.parse(upres.data);
							if (obj.code) {
								resolve(obj.data.fullurl)
							} else {
								reject(obj.msg)
							}
						},
						fail: (err) => {},
						complete: (com) => {}
					});
				})
			},
			fileName() {
				var date = new Date;
				var year = date.getFullYear();
				var month = date.getMonth() + 1;
				return 'shop_logo/' + year + "-" + month + "/" + Date.parse(new Date()) + parseInt(
					Math.random() * (100000 - 10000 + 1) + 10000, 10) + ".png";
			},
			getShouxieEngurl(img) {
				userApi.getShouxieEngurl({
					img: img
				}).then(result => {
					uni.$u.toast('修改成功');
				})
			},
			fanhuiTap() {
				this.pointsNum = [];
				uni.navigateBack()
			},
			close() {
				this.$emit('close');
			},
		}
	}
</script>

<style scoped lang="scss">
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		align-items: flex-end;
		animation: fadeIn 0.3s ease;
	}

	.modal-content {
		background: #fff;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		max-height: 80vh;
		display: flex;
		flex-direction: column;
		animation: slideUp 0.3s ease;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.modal-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.close-btn {
		font-size: 48rpx;
		color: #999;
		cursor: pointer;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.modal-body {
		flex: 1;
		padding: 30rpx;
		overflow-y: auto;
	}

	.signature-area {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.signature-title {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.sign-canvas {
		width: 100%;
		height: 400rpx;
		border: 2rpx solid #ddd;
		border-radius: 16rpx;
		background: #fff;
		touch-action: none;
	}

	.modal-footer {
		display: flex;
		padding: 30rpx;
		gap: 20rpx;
		border-top: 1rpx solid #eee;
	}

	.btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 12rpx;
		border: none;
		font-size: 28rpx;
		font-weight: 500;
		cursor: pointer;
	}

	.btn-cancel {
		background: #f5f5f5;
		color: #666;
	}

	.btn-cancel:active {
		background: #e0e0e0;
	}

	.btn-clear {
		background: #fff;
		color: #409eff;
		border: 2rpx solid #409eff;
	}

	.btn-clear:active {
		background: #f0f8ff;
	}

	.btn-submit {
		background: #409eff;
		color: #fff;
	}

	.btn-submit:active {
		background: #337ecc;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}
</style>